package com.lagou.edu.utils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author 赵虎
 * @date 2020/11/16 10:50
 */
public class WebClassLoader extends ClassLoader {

    private String basePath;

    public WebClassLoader(String basePath) {
        this.basePath = basePath + "/WEB-INF/classes/";
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] bytes = null;

        Path path = Path.of(basePath + name.replace(".", "/") + ".class");

        if (Files.exists(path)) {
            try {
                bytes = Files.readAllBytes(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bytes == null) {
            throw new ClassNotFoundException();
        }
        return defineClass(name, bytes, 0, bytes.length);
    }
}
